/**
 * Created by Jancheng on 2017/9/13.
 */
/**
 * 获取浏览器版本
 */
import exif from "exif-js"
// import http from '@/utils/httpClient'
// import config from '@/config/index';

/**
 * 获取浏览器版本
 * @returns {{trident: boolean, presto: boolean, webKit: boolean, gecko: boolean, mobile: boolean, ios: boolean, android: boolean, iPhone: boolean, iPad: boolean, webApp: boolean, qtClient: boolean, userAgent: string}}
 */
function getBrowserVersions(){
  var u = navigator.userAgent,app = navigator.appVersion;
  return {
    trident: u.indexOf('Trident') > -1, //IE内核
    presto: u.indexOf('Presto') > -1, //opera内核
    webKit: u.indexOf('AppleWebKit') > -1, //苹果、谷歌内核
    gecko: u.indexOf('Gecko') > -1 && u.indexOf('KHTML') == -1, //火狐内核
    mobile: !!u.match(/AppleWebKit.*Mobile.*/), //是否为移动终端
    ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), //ios终端
    android: u.indexOf('Android') > -1 || u.indexOf('Linux') > -1, //android终端或者uc浏览器
    iPhone: u.indexOf('iPhone') > -1 || u.indexOf('Mac') > -1, //是否为iPhone或者QQHD浏览器
    iPad: u.indexOf('iPad') > -1, //是否iPad
    webApp: u.indexOf('Safari') == -1 ,//是否web运用程序，没有头部与底部
    qtClient: u.indexOf('Qingtui')> -1 ,//轻推客户端
    userAgent:u
  };
}

/*判断*/
function checkisMobile() {
  //（1）拦截手机
  //（2）拦截浏览器/轻推PC客户端
  if(getBrowserVersions().iPhone||getBrowserVersions().android){

    return true;
  }else{
    return false;
  }
}
/**
 *读取图片文件
 * @param files：文件数组
 * 返回文件数组 [{name:'',src:''}]
 */
function readFilesToBase64(files){
  let p=new Promise(function(resolve, reject){
    let maxSize = 200 * 1024;//200kb
    let returnData=new Array();
    let currentLength=0;
    for (var i = 0; i < files.length; i++) {
      var reader = new FileReader();
      var orientation = '';
      exif.getData(files[i], function () {
        orientation = exif.getTag(this, 'Orientation');
      });
      reader.onload = function () {
        let fileObj=new Object();//文件对象
        fileObj.id="";
        var result = this.result;  //result为data url的形式
        if (result.length < maxSize) {
          fileObj.src=result;
          currentLength++;
          returnData.push(fileObj);
          //处理结束后
          if(currentLength==files.length){
            resolve(returnData);
          }
        }else{
          //图片压缩/转码
          compress(result,orientation).then(function(result){
            fileObj.src=result;
            currentLength++;
            returnData.push(fileObj);
            //处理结束后
            if(currentLength==files.length){
              resolve(returnData);
            }
          });
        }
      }
      reader.readAsDataURL(files[i]);
    }
  });
  return p;
}
/**
 * 图片压缩转码base64
 * @param data：数据
 * @param orientation:方向
 * @param name：名字
 */
function compress(data,orientation) {
  let p=new Promise(function (resolve,reject){
    var maxWidth=1024;
    var img = new Image();
    img.onload = function () {
      var degree = 0,drawWidth,drawHeight,width,height;
      drawHeight = this.naturalHeight;
      drawWidth = this.naturalWidth;
      //change photo size
      var maxSide = Math.max(drawWidth, drawHeight);
      if (maxSide > maxWidth) {
        var minSide = Math.min(drawWidth, drawHeight);
        minSide = minSide / maxSide * maxWidth;
        maxSide = maxWidth;
        if (drawWidth > drawHeight) {
          drawWidth = maxSide;
          drawHeight = minSide;
        } else {
          drawWidth = minSide;
          drawHeight = maxSide;
        }
      }
      let canvas=new Object();
      if(document.getElementsByTagName("canvas")==null){
        canvas=document.getElementsByTagName("canvas");
      }else{
        canvas =document.createElement('canvas');
      }
      canvas.width = width = drawWidth;
      canvas.height = height = drawHeight;
      var context = canvas.getContext('2d');
      //判断图片方向，重置canvas大小，确定旋转角度，iphone默认的是home键在右方的横屏拍摄方式
      switch (orientation) {
        //iphone横屏拍摄，此时home键在左侧
        case 3:
          degree = 180;
          drawWidth = -width;
          drawHeight = -height;
          break;
        //iphone竖屏拍摄，此时home键在下方(正常拿手机的方向)
        case 6:
          canvas.width = height;
          canvas.height = width;
          degree = 90;
          drawWidth = width;
          drawHeight = -height;
          break;
        //iphone竖屏拍摄，此时home键在上方
        case 8:
          canvas.width = height;
          canvas.height = width;
          degree = 270;
          drawWidth = -width;
          drawHeight = height;
          break;
      }
      //使用canvas旋转校正
      context.rotate(degree * Math.PI / 180);
      context.drawImage(this, 0, 0, drawWidth, drawHeight);
      //返回校正图片
      resolve(canvas.toDataURL("image/jpeg",0.8));
    };
    img.src = data;
  });
  return p;
}

function getObjectTextCount(id) {
  if(id!=undefined&&id!=null&&document.getElementById(id)){
    return document.getElementById(id).innerText.length;
  }else{
    return 0;
  }
}

/**
 * 检查Dom Text 与Max大小
 * @param id
 * @param max
 */

export default {
  getBrowserVersions,
  checkisMobile,
  readFilesToBase64,
  getObjectTextCount,

};
